package com.lib.updater;

import android.app.DownloadManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.HandlerThread;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;

public class Updater {
    private static Updater instance;
    private HandlerThread mDownHandlerThread;
    private DownloadContentObserver downloadContentObserver;

    private boolean isInit;

    public static Updater getInstance() {
        if (instance == null) {
            synchronized (Updater.class) {
                if (instance == null) {
                    instance = new Updater();
                }
            }
        }
        return instance;
    }

    private Updater() {
        isInit = true;
        mDownHandlerThread = new HandlerThread("download");
        mDownHandlerThread.start();
    }

    /**
     * 获取Downloader的整体looper
     *
     * @return
     */
    static Looper getLooper() {
        return getInstance().mDownHandlerThread.getLooper();
    }

    /**
     * 销毁事件
     */
    public static void release(Context context) {
        getInstance().releaseDL(context);
    }

    private void releaseDL(Context context) {
        if (isInit) {
            isInit = false;
            if (downloadContentObserver != null) {
                downloadContentObserver.setUpdateListener(null);
                context.getContentResolver().unregisterContentObserver(downloadContentObserver);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                mDownHandlerThread.quitSafely();
            } else {
                mDownHandlerThread.quit();
            }
            mDownHandlerThread = null;
            downloadContentObserver = null;
            instance = null;
        }
    }


    public static void update(Context context, UpdaterConfig config) {
        getInstance().down(context, config, null);
    }

    public static void update(Context context, UpdaterConfig config, UpdateListener listener) {
        getInstance().down(context, config, listener);
    }

    private void down(Context context, UpdaterConfig config, UpdateListener listener) {
        if (!UpdaterUtils.checkDownloadState(context)) {
            Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
            UpdaterUtils.showDownloadSetting(context);
            return;
        }
        long downloadId = UpdaterUtils.getLocalDownloadId(context);
        Logger.get().d("local download id is " + downloadId);
        if (downloadId != -1L) {
            Downloader fdm = Downloader.getInstance();
            //获取下载状态
            int status = fdm.getDownloadStatus(context, downloadId);
            switch (status) {
                //下载成功
                case DownloadManager.STATUS_SUCCESSFUL:
                    Uri uri = fdm.getDownloadUri(context, downloadId);
                    if (uri != null) {
                        //本地的版本大于当前程序的版本直接安装
                        if (UpdaterUtils.compare(context, uri.getPath())) {
                            installApk(context, downloadId);
                            return;
                        } else {
                            //从FileDownloadManager中移除这个任务
                            fdm.getDM(context).remove(downloadId);
                        }
                    }
                    //重新下载
                    long id = fdm.startDownload(context, config);
                    if (listener != null) {
                        uri = Uri.parse("content://downloads/my_downloads");
                        downloadContentObserver = new DownloadContentObserver(context);
                        downloadContentObserver.setDownloadId(id);
                        downloadContentObserver.setUpdateListener(listener);
                        context.getContentResolver().registerContentObserver(uri, true, downloadContentObserver);
                    }
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    id = fdm.startDownload(context, config);
                    if (listener != null) {
                        uri = Uri.parse("content://downloads/my_downloads");
                        downloadContentObserver = new DownloadContentObserver(context);
                        downloadContentObserver.setDownloadId(id);
                        downloadContentObserver.setUpdateListener(listener);
                        context.getContentResolver().registerContentObserver(uri, true, downloadContentObserver);
                    }
                    break;
                case DownloadManager.STATUS_RUNNING:
                    break;
                case DownloadManager.STATUS_PENDING:
                    break;
                case DownloadManager.STATUS_PAUSED:
                    break;
                default:
                    break;
            }
        } else {
            long id = Downloader.getInstance().startDownload(context, config);
            if (listener != null) {
                Uri uri = Uri.parse("content://downloads/my_downloads");
                downloadContentObserver = new DownloadContentObserver(context);
                downloadContentObserver.setDownloadId(id);
                downloadContentObserver.setUpdateListener(listener);
                context.getContentResolver().registerContentObserver(uri, true, downloadContentObserver);
            }
        }
    }

    public static void cancel(Context context) {
        getInstance().remove(context);
    }

    private void remove(Context context) {
        Downloader.getInstance().getDM(context).remove(UpdaterUtils.getLocalDownloadId(context));
    }

    private void installApk(final Context context, long downloadApkId) {
        Uri downloadFileUri = Downloader.getInstance().getDM(context).getUriForDownloadedFile(downloadApkId);
        if (downloadFileUri != null) {
            String path = getRealFilePath(context, downloadFileUri);
            final File file = new File(path);
            if (file.exists()) {
                AndPermission.with(context)
                        .install()
                        .file(file)
                        .rationale(new InstallRationale())
                        .start();
            } else {
                Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Logger.get().d("download failed");
        }
    }


    private static String getRealFilePath(Context context, Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private static void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uriForFile = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, context.getContentResolver().getType(uriForFile));
        } else {
            intent.setDataAndType(Uri.fromFile(file), getMIMEType(file));
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }
    }

    private static String getMIMEType(File file) {
        String var1 = "";
        String var2 = file.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

    public interface UpdateListener {
        void process(long process, long max);
    }
}
